<template>
  <div class="blog-type-manage">
    <div class="page-header">
      <h2 class="page-title">博客分类管理</h2>
      <button class="btn btn-primary" @click="openCreateTypeModal">
        <i class="fas fa-plus"></i> 新建分类
      </button>
    </div>

    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
    </div>

    <div v-else-if="error" class="error-message">
      {{ error }}
    </div>

    <div v-else-if="blogTypes.length === 0" class="empty-state">
      <div class="empty-icon">
        <i class="fas fa-folder-open"></i>
      </div>
      <h3>暂无博客分类</h3>
      <p>您尚未创建任何博客分类，点击"新建分类"按钮创建您的第一个分类。</p>
      <button class="btn btn-primary" @click="openCreateTypeModal">
        <i class="fas fa-plus"></i> 新建分类
      </button>
    </div>

    <div v-else class="blog-types-list">
      <div class="blog-types-header">
        <div class="type-name-header">分类名称</div>
        <div class="type-count-header">文章数量</div>
        <div class="type-date-header">创建时间</div>
        <div class="type-actions-header">操作</div>
      </div>

      <div 
        v-for="type in blogTypes" 
        :key="type.typeId" 
        class="blog-type-item"
      >
        <div class="type-name">{{ type.typeName }}</div>
        <div class="type-count">{{ type.blogCount || 0 }}</div>
        <div class="type-date">{{ formatDate(type.createTime) }}</div>
        <div class="type-actions">
          <button 
            class="btn btn-sm btn-primary" 
            @click="openEditTypeModal(type)"
            title="编辑"
          >
            <i class="fas fa-edit"></i>
          </button>
          <button 
            class="btn btn-sm btn-danger" 
            @click="confirmDeleteType(type)"
            title="删除"
            :disabled="type.blogCount > 0"
          >
            <i class="fas fa-trash"></i>
          </button>
        </div>
      </div>

      <div class="blog-types-footer">
        共 {{ blogTypes.length }} 个分类
      </div>
    </div>

    <!-- 创建/编辑分类弹窗 -->
    <div class="modal" v-if="showTypeModal">
      <div class="modal-backdrop" @click="closeTypeModal"></div>
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h3 class="modal-title">{{ isEditing ? '编辑分类' : '创建新分类' }}</h3>
            <button type="button" class="btn-close" @click="closeTypeModal">
              &times;
            </button>
          </div>
          <div class="modal-body">
            <div class="form-group">
              <label for="typeName" class="form-label">分类名称</label>
              <input 
                type="text" 
                id="typeName" 
                v-model="typeForm.typeName" 
                class="form-input"
                placeholder="请输入分类名称"
                maxlength="50"
              />
            </div>
            <div v-if="typeMessage" class="message" :class="typeMessageType">
              {{ typeMessage }}
            </div>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              @click="closeTypeModal"
              :disabled="typeSubmitting"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-primary"
              @click="submitTypeForm"
              :disabled="typeSubmitting"
            >
              {{ typeSubmitting ? '提交中...' : '确认' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认弹窗 -->
    <div class="modal" v-if="showDeleteModal">
      <div class="modal-backdrop" @click="closeDeleteModal"></div>
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <h3 class="modal-title">确认删除</h3>
            <button type="button" class="btn-close" @click="closeDeleteModal">
              &times;
            </button>
          </div>
          <div class="modal-body">
            <p v-if="selectedType && selectedType.blogCount > 0" class="text-danger">
              <i class="fas fa-exclamation-triangle"></i>
              该分类下有 {{ selectedType.blogCount }} 篇博客，不能删除！
            </p>
            <p v-else>
              确定要删除分类"{{ selectedType?.typeName }}"吗？此操作不可恢复。
            </p>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-secondary"
              @click="closeDeleteModal"
              :disabled="deleteSubmitting"
            >
              取消
            </button>
            <button
              type="button"
              class="btn btn-danger"
              @click="deleteType"
              :disabled="deleteSubmitting || (selectedType && selectedType.blogCount > 0)"
            >
              {{ deleteSubmitting ? '删除中...' : '删除' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { useTypeStore } from '@/store/type'

const router = useRouter()
const authStore = useAuthStore()
const typeStore = useTypeStore()

// 数据与状态
const blogTypes = ref([])
const loading = ref(false)
const error = ref(null)

// 表单与弹窗相关
const showTypeModal = ref(false)
const showDeleteModal = ref(false)
const isEditing = ref(false)
const typeForm = ref({
  typeId: null,
  typeName: ''
})
const typeMessage = ref('')
const typeMessageType = ref('info')
const typeSubmitting = ref(false)
const deleteSubmitting = ref(false)
const selectedType = ref(null)

// 初始化数据
onMounted(async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login')
    return
  }
  
  await loadBlogTypes()
})

// 加载博客类型列表
const loadBlogTypes = async () => {
  try {
    loading.value = true
    error.value = null
    
    const types = await typeStore.getUserBlogTypes()
    blogTypes.value = types || []
  } catch (err) {
    error.value = err.message || '加载博客分类失败'
    console.error(err)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 打开创建分类弹窗
const openCreateTypeModal = () => {
  isEditing.value = false
  typeForm.value = {
    typeId: null,
    typeName: ''
  }
  typeMessage.value = ''
  showTypeModal.value = true
}

// 打开编辑分类弹窗
const openEditTypeModal = (type) => {
  isEditing.value = true
  typeForm.value = {
    typeId: type.typeId,
    typeName: type.typeName
  }
  typeMessage.value = ''
  showTypeModal.value = true
}

// 关闭类型弹窗
const closeTypeModal = () => {
  showTypeModal.value = false
}

// 提交类型表单（创建或编辑）
const submitTypeForm = async () => {
  if (!typeForm.value.typeName.trim()) {
    typeMessage.value = '请输入分类名称'
    typeMessageType.value = 'error'
    return
  }
  
  try {
    typeSubmitting.value = true
    typeMessage.value = ''
    
    if (isEditing.value) {
      // 编辑现有分类
      await typeStore.updateBlogType(
        typeForm.value.typeId,
        typeForm.value.typeName.trim()
      )
      typeMessage.value = '分类更新成功'
    } else {
      // 创建新分类
      await typeStore.createBlogType(typeForm.value.typeName.trim())
      typeMessage.value = '分类创建成功'
    }
    
    typeMessageType.value = 'success'
    
    // 刷新类型列表并短暂延迟后关闭弹窗
    await loadBlogTypes()
    setTimeout(() => {
      closeTypeModal()
    }, 1000)
  } catch (err) {
    typeMessage.value = err.message || '操作失败'
    typeMessageType.value = 'error'
  } finally {
    typeSubmitting.value = false
  }
}

// 确认删除分类
const confirmDeleteType = (type) => {
  if (type.blogCount > 0) {
    // 如果分类下有博客，显示提示但不允许删除
    selectedType.value = type
    showDeleteModal.value = true
    return
  }
  
  selectedType.value = type
  showDeleteModal.value = true
}

// 关闭删除确认弹窗
const closeDeleteModal = () => {
  showDeleteModal.value = false
}

// 执行删除操作
const deleteType = async () => {
  if (!selectedType.value || selectedType.value.blogCount > 0) {
    return
  }
  
  try {
    deleteSubmitting.value = true
    
    await typeStore.deleteBlogType(selectedType.value.typeId)
    
    // 刷新类型列表
    await loadBlogTypes()
    closeDeleteModal()
  } catch (err) {
    error.value = err.message || '删除失败'
  } finally {
    deleteSubmitting.value = false
  }
}
</script>

<style scoped>
.blog-type-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 1.8rem;
  color: #333;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 50px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-message {
  background-color: #ffebee;
  color: #d32f2f;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 50px 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.empty-icon {
  font-size: 3rem;
  color: #bbb;
  margin-bottom: 20px;
}

.empty-state h3 {
  margin-bottom: 10px;
  color: #555;
}

.empty-state p {
  margin-bottom: 20px;
  color: #777;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.blog-types-list {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.blog-types-header {
  display: grid;
  grid-template-columns: 3fr 1fr 2fr 1fr;
  gap: 15px;
  padding: 15px 20px;
  background-color: #f5f5f5;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}

.blog-type-item {
  display: grid;
  grid-template-columns: 3fr 1fr 2fr 1fr;
  gap: 15px;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  align-items: center;
}

.blog-type-item:last-child {
  border-bottom: none;
}

.blog-type-item:hover {
  background-color: #f9f9f9;
}

.type-name {
  font-weight: 500;
}

.type-count {
  color: #666;
  text-align: center;
}

.type-date {
  color: #666;
}

.type-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.blog-types-footer {
  padding: 15px 20px;
  background-color: #f5f5f5;
  color: #666;
  font-size: 0.9rem;
  text-align: right;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-dialog {
  width: 100%;
  max-width: 500px;
  position: relative;
  z-index: 1001;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
}

.modal-title {
  margin: 0;
  font-size: 1.25rem;
}

.btn-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #888;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 15px 20px;
  border-top: 1px solid #eee;
}

.form-group {
  margin-bottom: 15px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
  box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

.message {
  margin-top: 10px;
  padding: 10px;
  border-radius: 4px;
}

.message.error {
  background-color: #ffebee;
  color: #d32f2f;
}

.message.success {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.message.info {
  background-color: #e3f2fd;
  color: #1976d2;
}

.text-danger {
  color: #d32f2f;
}

.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  border: none;
  transition: background-color 0.2s, box-shadow 0.2s;
}

.btn-primary {
  background-color: #3498db;
  color: white;
}

.btn-primary:hover {
  background-color: #2980b9;
}

.btn-secondary {
  background-color: #ecf0f1;
  color: #34495e;
}

.btn-secondary:hover {
  background-color: #dde4e6;
}

.btn-danger {
  background-color: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background-color: #c0392b;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 0.875rem;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn i {
  margin-right: 5px;
}

@media (max-width: 768px) {
  .blog-types-header,
  .blog-type-item {
    grid-template-columns: 2fr 1fr 1fr;
  }
  
  .type-date-header,
  .type-date {
    display: none;
  }
}

@media (max-width: 576px) {
  .blog-types-header,
  .blog-type-item {
    grid-template-columns: 2fr 1fr;
  }
  
  .type-count-header,
  .type-count {
    display: none;
  }
}
</style> 